<?php

namespace App\Admin\Controllers;

use Encore\Admin\Form;
use Encore\Admin\Widgets\Form as FormWidget;
use Encore\Admin\Widgets\Table;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Row;
use Encore\Admin\Layout\Column;

use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Http\Request;
use App\Models\Article;
use App\Models\Collection;
use App\Models\CollectionArticle;
use App\Admin\Extensions\Tools\AddToCollection;

class CollectionArticleController extends Controller
{
    private $cid; //collection id

    use ModelForm;
    
    /**
     * Index interface.
     *
     * @return Content
     */
    public function index(Request $request, $cid)
    {
        $this->cid = $cid;
        Admin::script($this->script());
        return Admin::content(function (Content $content) {

            $content->header('Collection Articles');
            $content->description('List');
            $content->row(function(Row $row) {

                $collection = Collection::find($this->cid);
                $row->column(6, function (Column $column) {
                    $column->append((new Box(trans('admin.search_articles'), $this->searchGird()->render()))->style('success')->collapsable());
                });

                $row->column(6, function (Column $column) use ($collection) {
                    $style = '<style>.box-collection { min-height: 800px; }</style>';
                    $column->append((new Box(trans('admin.collection') . ': ' . $collection->name, $style . $this->grid()->render()))->style(['info', 'collection']));
                });
            });

            // $content->body();
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('Collection Articles');
            $content->description('List');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('Collection Articles');
            $content->description('List');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(CollectionArticle::class, function (Grid $grid) {
            $cid = $this->cid;
            $grid->model()->where('c_id', $cid);
            $grid->setName('c');
            $grid->article()->id('Article ID');

            $grid->article()->title('Title');

            $grid->disableExport();
            $grid->disableFilter();
            $grid->disableCreateButton();
            $grid->disablePagination();

            $grid->actions(function (Grid\Displayers\Actions $actions) use ($cid) {
                // $actions->disableDelete();
                $actions->disableEdit();
                $actions->disableView();
            });
        });

        $table = new Table();

    }


    protected function searchGird()
    {
        return Admin::grid(Article::class, function (Grid $grid) {
            $grid->setName('s');
            $grid->paginate(20);
            $grid->id('Article ID');

            $grid->title('Title');

            $grid->disableExport();
            $grid->disableCreateButton();
            
            $cid = $this->cid;
            $grid->actions(function (Grid\Displayers\Actions $actions) use ($cid) {
                $actions->disableDelete();
                $actions->disableEdit();
                $actions->disableView();

                $actions->append('<a class="add-to-collection" data-add-url="' .route('collection_articles.add', ['cid' => $cid]). '?aid=' . $actions->getKey() .'" href="#" style="width: 40px; display:inline-block;">添加</a>');
            });

            $grid->tools(function (Grid\Tools $tools) {
                $tools->batch(function (Grid\Tools\BatchActions $actions) {
                    $actions->disableDelete();

                    $actions->add('批量添加', new AddToCollection($this->cid));
                });
            });


            $grid->filter(function($filter) {
                $filter->disableIdFilter();
                $type = 'title';
                $filter->where(function($query) use (&$type) {
                    $type = $this->input;
                }, 'Type', 'type')->select([
                    'id' => 'ID',
                    'title' => 'Title',
                    'keywords' => 'Keywords'
                ])->default('title');


                $filter->where(function($query) use (&$type) {
                    switch ($type) {
                        case 'id':
                            $query->where('id', $this->input);
                            break;

                        case 'title':
                            $query->where('title', 'like', '%' . $this->input . '%');
                            break;

                        default:
                            $query->where('title', 'like', '%' . $this->input . '%')
                                ->orWhere('abstract', 'like', '%' . $this->input . '%')
                                ->orWhere('keywords', 'like', '%' . $this->input . '%');
                            break;
                    }
                }, '', 'keyword')->placeholder('请输入。。。');

                
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(CollectionArticle::class, function (Form $form) {

            $form->display('id', 'ID');

            $form->display('created_at', 'Created At');
            $form->display('updated_at', 'Updated At');
        });
    }

    public function batchAddArticle(Request $request, $cid)
    {
        $collection = Collection::find($cid);
        if (!$collection) {
            abort(404, 'can not get collection, Collection ID: ' . $cid);
        }

        $ids = $request->input('ids', []);
        if (!empty($ids)) {
            array_map(function ($id) use ($cid) {
                return CollectionArticle::firstOrCreate(['c_id' => $cid, 'a_id' => $id ]);
            }, $ids);
        } else {
            abort(404, 'Please choose Article first.');
        }

        return response('done');
    }


    public function addArticle(Request $request, $cid)
    {
        $collection = Collection::find($cid);
        if (!$collection) {
            abort(404, 'can not get collection, Collect ID: ' . $cid);
        }

        if ($aid = $request->input('aid')) {
            return CollectionArticle::firstOrCreate(['c_id' => $cid, 'a_id' => $aid ]);
        } else {
            abort(404, 'Please choose Article first.');
        }

        return response('done');
    }
    public function delete($cid, $id)
    {
        return CollectionArticle::destroy(explode(',', $id));
    }

    public function script()
    {
        $list = '<a class="btn btn-xs btn-info" href="' . route('collections.index') . '"><i class="fa fa-list-ul"></i> 专辑列表</a>';
        $token = csrf_token();
        return <<<EOT
$('.add-to-collection').click(function(e) {
    console.log(12)
    e.preventDefault();
    var url = $(this).data('add-url');
    $.ajax({
        method: 'post',
        url: url,
        data: {
            _token:'{$token}',
        },
        success: function (res) {
            $.pjax.reload('#pjax-container');
            toastr.success('操作成功');
            },
            error: function(err) {
                alert(err.responseJSON.message);
            }
    })
});

$('.box-collection').find('.box-tools').append('{$list}');

EOT;
    }
}
